﻿/****
 *    小程序图片上传/显示API
 * 
 * 
 * 
 * *****/
namespace aier.wx.api.selfhost.Controllers
{
    using aier.business.logic;
    using aier.dataaccess.model;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Reflection;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Linq;
    using log4net;

    [RoutePrefix("api/Attachment")]
    public class AttachmentController : ApiController
    {
        /// <summary>
        /// 日志
        /// </summary>
        public ILog log { get; set; }

        public AttachmentBll attachmentBll { get; set; }

        public ApiTool apiTool { get; set; }

        //Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
        private readonly string imgPathBase = System.Configuration.ConfigurationManager.AppSettings["imgPathBase"];

        [HttpGet]
        [ActionName("GetTAttachments")]
        public IHttpActionResult GetTAttachments(string outerid) {
             var imageNameList = attachmentBll.FindTAttachments(outerid).Select(t => t.ATTDIR);
            //var imageNameList = attachmentBll.FindTAttachments(outerid);
            return Ok(imageNameList);
        }


        /// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="outerid"></param>
        /// <returns></returns>
        public async Task<IHttpActionResult> Get(string imgName, int height, int width)
        {
            imgName = imgName.Substring(imgName.LastIndexOf('/') + 1);
            string imgSuffix = ".jpg";

            imgSuffix = imgName.Substring(imgName.LastIndexOf('.'));
            try
            {
               
                var path = string.Concat(imgPathBase, "/App_Data/");
                var root = new Uri(path).LocalPath;
                var imgPath = string.Concat(root, imgName);

                var fileByte = await Task.Factory.StartNew<byte[]>(() =>
                {
                    return File.ReadAllBytes(imgPath);
                });

                var imgStream = new MemoryStream(fileByte);

                var imgByte = apiTool.toImage(imgStream, imgSuffix, height, width);

                return new ImageResult(imgByte, $"image/{imgSuffix.Replace(".",string.Empty)}");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + ex.StackTrace, ex);
                return new ApiErrorResult(ex.StackTrace, Request);
            }

        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [ActionName("DelAttachment")]
        public async Task<IHttpActionResult> DelAttachment(string dir) {
            ResResult resResult =  attachmentBll.ModAttStateByDir(dir);
            return Ok(resResult);
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [ActionName("PostAttachment")]
        public async Task<IHttpActionResult> PostAttachment()
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                //获取基础信息
                UserInfo userInfo = apiTool.GetLoginUser(RequestContext);
                Guid ownerId = userInfo.userid; //当前用户
                Guid guid = Guid.Empty;//实体id
                //Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                //string imgPathBase = System.Configuration.ConfigurationManager.AppSettings["imgPathBase"]; 
                var path = string.Concat(imgPathBase, "/App_Data/");
                var root = new Uri(path).LocalPath;

                var provider = new CustomMultipartFormDataStreamProvider(root);

                var multipartMemoryStreamProvider = await Request.Content.ReadAsMultipartAsync(provider);
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        //string formDate = string.Format("{0}: {1}", key, val);
                        if (key.Equals("entityId")) {
                            guid = new Guid(val);
                            break;
                        }
                    }
                }
               
                foreach (MultipartFileData file in provider.FileData)
                {
                    string fileName = file.Headers.ContentDisposition.FileName;
                    string localFileName = file.LocalFileName;
                    //创建一条附件记录
                    string attid = apiTool.GetRandomStr("ATID"); // 主键
                  
                    attachmentBll.SaveAttachment(attid,fileName, ownerId, guid);
                }
              
                return Ok();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message+ex.StackTrace, ex);
                return new ApiErrorResult(ex.StackTrace, Request);
            }
        }
    }
}
